package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.DealModel;
import models.OrderModel;
import models.OrderProductModel;
import models.StoreItemModel;
import models.TransactionModel;
import admin.data.DealData;
import admin.data.OrderData;
import admin.data.StoreItemData;
import admin.data.TransactionData;
import data.GeoData;

@SuppressWarnings("serial")
public class ProcessOrderServlet extends HttpServlet {

	private static final Logger log = Logger
			.getLogger(ProcessOrderServlet.class.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		try {
			String strIds = (String) request.getParameter("ids");
			String action = (String) request.getParameter("action");
			TimeZone localTimeZone = TimeZone.getTimeZone("GMT+07:00");
			TimeZone.setDefault(localTimeZone);
			Calendar.getInstance().setTimeZone(localTimeZone);
			String[] ids = strIds.split(",");
			if (action != null) {
				int intAction = 1;
				try {
					intAction = Integer.parseInt(action);
				} catch (Exception e) {
					intAction = 1;
				}
				if (intAction == 8) {
					// direct sell.
					for (int i = 0; i < ids.length; i++) {
						if (!ids[i].isEmpty()) {
							boolean check = true;
							OrderModel order = OrderData.getById(ids[i]);
							List<String> listStringProduct = order
									.getListOrderProduct();
							List<StoreItemModel> listStoreItem = new ArrayList<StoreItemModel>();
							List<TransactionModel> listTransaction = new ArrayList<TransactionModel>();
							StoreItemData storeItemData = new StoreItemData();
							TransactionData transactionData = new TransactionData();
							StoreItemModel storeItemModel;
							for (String string : listStringProduct) {
								OrderProductModel orderPr = new OrderProductModel();
								orderPr.getValueFromString(string);
								storeItemModel = new StoreItemModel();
								storeItemModel = storeItemData.getItem(orderPr
										.getProductId());
								if (storeItemModel != null
										&& (storeItemModel.getInventory() >= orderPr
												.getQuantity())) {
									// nếu đơn hàng chưa xử lý
									if (order.getStatus() == 1) {
										storeItemModel
												.setInventory(storeItemModel
														.getInventory()
														- orderPr.getQuantity());
										listStoreItem.add(storeItemModel);
										// thực hiện lưu transaction.
										TransactionModel transaction = new TransactionModel();
										transaction
												.setTransactionId(IdUniqueHelper
														.getId());
										transaction.setDealId(storeItemModel
												.getDealId());
										transaction
												.setStoreItemId(storeItemModel
														.getId());
										transaction.setInventory(storeItemModel
												.getInventory());
										transaction.setDelivered(storeItemModel
												.getDelivered());
										transaction.setDelivery(storeItemModel
												.getDelivery());
										transaction.setLoc(storeItemModel
												.getLoc());
										transaction.setType(0);
										transaction.setDate(Calendar
												.getInstance().getTime());
										transaction.setAmount(orderPr
												.getQuantity());
										listTransaction.add(transaction);
									}

								} else {
									check = false;
								}
							}
							if (check) {
								for (int j = 0; j < listStoreItem.size(); j++) {
									storeItemData.insert(listStoreItem.get(j));
									transactionData.insert(listTransaction
											.get(j));
								}
								order.setStatus(4);
								order.setCheckOut(true);
								order.setCheckOutTime(Calendar.getInstance().getTime());
								OrderData.insert(order);
							} else {
								response.setCharacterEncoding("UTF-8");
								response.getWriter()
										.println(
												"Số lượng sản phẩm trong kho không đủ để hoàn thành đơn hàng ! Vui lòng kiểm tra lại số lượng sản phẩm trong kho.");
							}
						}
					}
				} else if (intAction == 11) {
					// direct sell với hình thức thanh toán chuyển khoản.
					for (int i = 0; i < ids.length; i++) {
						if (!ids[i].isEmpty()) {
							OrderModel order = OrderData.getById(ids[i]);
							if (order != null && order.getPaymentType() == 2) {
								order.setCheckOut(true);
								order.setCheckOutTime(Calendar.getInstance().getTime());
								OrderData.insert(order);
							} else {
								response.setCharacterEncoding("UTF-8");
								response.getWriter()
										.println(
												"Đơn hàng không tồn tại hoặc không thể xác nhận thanh toán chuyển khoản.");
							}
						}
					}
				} else if (intAction == 5) {
					// hủy đơn hàng
					for (int i = 0; i < ids.length; i++) {
						if (!ids[i].isEmpty()) {
							OrderModel order = OrderData.getById(ids[i]);
							order.setStatus(intAction);
							DealModel deal = DealData
									.getById(order.getDealId());
							if (deal != null) {
								int amount = deal.getAmount()
										- order.getQuantity();
								if (amount < 0) {
									amount = 0;
								}
								deal.setAmount(amount);
								if (deal.getEndTime().compareTo(
										Calendar.getInstance().getTime()) > 0
										&& deal.getAmount() < deal.getLimit()) {
									deal.setStatus(2);
								}
								DealData.insert(deal);
							}
							OrderData.insert(order);
						}
					}
				} else {

				}
			}
		} catch (Exception e) {
			System.out
					.println("Error when try to process order from admin page !");
			log.warning("Error when try to process order from admin page !");
			log.warning(e.toString());
			e.printStackTrace();
		}

	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String orderId = request.getParameter("orderId");
		String shipType = request.getParameter("shipType");
		String address = request.getParameter("address");
		String city = request.getParameter("city");
		String district = request.getParameter("district");
		String ward = request.getParameter("ward");
		String note = request.getParameter("note");
		OrderModel order = OrderData.getById(orderId);
		if (order != null) {
			if (shipType != null && shipType.equals("1")) {
				boolean change = false;
				String oldAddress = "";
				if (order.getShipType() == 2) {
					oldAddress = "Nhận hàng tại onsale365.com.vn - Số 46 D2 Khu đô thị mới Đại Kim, Phường Đại Kim, Quận Hoàng Mai, Hà Nội";
					change = true;
				} else if (!order.getShipAddress().equals(address)
						|| !order.getShipCity().equals(city)
						|| !order.getShipDistrict().equals(district)
						|| !order.getShipWard().equals(ward)) {
					oldAddress = order.getShipAddressFull();
					change = true;
				} else if (note != null && !note.isEmpty()) {
					order.setNote(note);
					OrderData.insert(order);
				}
				if (change) {
					order.setChangeAddress(true);
					order.setOldAddress(oldAddress);
					order.setShipAddress(address);
					order.setShipCity(city);
					order.setShipDistrict(district);
					order.setShipWard(ward);
					order.setShipType(1);
					order.setNote(note != null ? note : "");
					GeoData geoData = new GeoData();
					StringBuilder temStr = new StringBuilder();
					if (order.getShipAddress() != null
							&& !order.getShipAddress().isEmpty()) {
						temStr.append(order.getShipAddress() + ", ");
					}
					if (order.getShipWard() != null
							&& !order.getShipWard().isEmpty()) {
						temStr.append(geoData.getGeo(order.getShipWard())
								.getName() + ", ");
					}
					if (order.getShipDistrict() != null
							&& !order.getShipDistrict().isEmpty()) {
						temStr.append(geoData.getGeo(order.getShipDistrict())
								.getName() + ", ");
					}
					if (order.getShipCity() != null
							&& !order.getShipCity().isEmpty()) {
						temStr.append(geoData.getGeo(order.getShipCity())
								.getName());
					}
					order.setShipAddressFull(temStr.toString());
					OrderData.insert(order);
				}
			} else {
				if (order.getShipType() != 2) {
					order.setChangeAddress(true);
					order.setOldAddress(order.getShipAddressFull());
					order.setShipAddress("");
					order.setShipAddressFull("Nhận hàng tại onsale365.com.vn - Số 46 D2 Khu đô thị mới Đại Kim, Phường Đại Kim, Quận Hoàng Mai, Hà Nội");
					order.setShipType(2);
					order.setNote(note != null ? note : "");
					OrderData.insert(order);
				}
			}
		} else {
			System.out.println("Trying to get not exits order !");
			log.warning("Trying to get not exits order !");
		}
	}
}
